/**
 * @author corleone
 * @date 2019/1/8 0008
 */
package com.xinnet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class XinnetSpider {

    public static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true).build();

    static Map<String, String> domain = new HashMap<>();

    public static void main(String[] args) throws IOException, InterruptedException {
        while (true) {
            exec();
            Thread.sleep(4000L);
        }
    }

    public static void exec() throws IOException {
        long now = System.currentTimeMillis();

        String url = "http://checksolr.xinnet.com/domain/domainBookSearch?callbackparam=jQuery" + now + "_" + now + "&domainName=&notDomainName=&deleteDate=&damainType=&location=contains&domainLengthStart=1&domainLengthEnd=5&domainKindType=NUM&domainXSType=&domainSuffix=.com&pageSize=100&pageNo=1&lengthSortDesc=false&_=" + now;

        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        try (Response execute = call.execute()) {
            String body = execute.body().string();
            String body1 = StringUtils.substringAfter(body, "(");
            String body2 = StringUtils.substringBeforeLast(body1, ")");
            JSONArray array = JSON.parseArray(body2);
            JSONObject jo = array.getJSONObject(0);
            if (jo.containsKey("list")) {
                for (Object o : jo.getJSONArray("list")) {
                    JSONObject row = (JSONObject) o;
                    String bookState = row.getString("bookState");
                    String domainName = row.getString("domainName");
                    if (bookState.equals("0")) {
                        System.out.print("\\n");
                        if (!domain.containsKey(domainName)) {
                            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "-->" + domainName + ":" + row);
                            domain.put(domainName, row.toString());
                        }
                    }
                }
                System.out.print(" ");
            }
        }
    }

}
